import { computed, ref, getCurrentInstance, onMounted, watch } from "vue";

interface Size {
  width: number;
  height: number;
}

/** 使用尺寸容器展开 */
export const useSizeBoxOpen = ({
  ruleCls,
  wrapCls,
  mode,
  watchTarget,
}: {
  /** 主体内容wrap类名 */
  wrapCls: string;
  /** 尺子类名 */
  ruleCls: string;
  /** 模式 */
  mode: "height" | "width";
  /** 监听目标 */
  watchTarget: Parameters<typeof watch>[0];
}) => {
  const isOpen = ref(false);

  const wrapSize = ref(0);

  const ruleSize = ref(0);

  const needToggle = computed(() => {
    return wrapSize.value > ruleSize.value;
  });

  const nodeQuery = uni.createSelectorQuery().in(getCurrentInstance());

  const updateWrapSize = () => {
    const wrap = nodeQuery.select(wrapCls);

    // console.error(90, wrap);

    wrap.fields(
      {
        size: true,
      },
      (data) => {
        // console.error(98, data);
        wrapSize.value = (data as Size)[mode];
      },
    );

    nodeQuery.exec();
  };

  const changeOpenStatus = (status = !isOpen.value) => {
    isOpen.value = status;
  };

  onMounted(() => {
    const rule = nodeQuery.select(ruleCls);

    // console.error(79, rule);

    rule.fields(
      {
        size: true,
      },
      (data) => {
        // console.error(87, data);
        ruleSize.value = (data as Size)[mode];
      },
    );

    nodeQuery.exec();

    watch(
      watchTarget,
      () => {
        updateWrapSize();
      },
      {
        flush: "post",
        immediate: true,
      },
    );
  });

  return {
    isOpen,
    needToggle,
    changeOpenStatus,
  };
};
